package com.billdowney.util.return_type;

import com.billdowney.exception.BizException;
import com.billdowney.util.CommonUtil;
import com.billdowney.util.spring.SpringUtil;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * HTTP返回数据类型为：data中是返回的数据，有可能会包含错误信息；code返回的提示代码，默认为10000；msg提示信息，根据code的值来自动变化
 * 
 * @author 超级小富翁 - BillDowney
 * @data 2016年12月16日 下午7:09:18
 */
@ApiModel(description = "请求返回的数据格式")
public class ReturnData {

	@ApiModelProperty(value = "后台处理代码", notes = "用于前台判断", dataType = "Integer")
	private Integer code = 10000;
	@ApiModelProperty(value = "处理返回到前台的数据", notes = "根据场景返回数据而定")
	private Object data;
	@ApiModelProperty(value = "后台处理信息", notes = "用于前台展示", dataType = "String")
	private String msg;

	public ReturnData() {
		this.setCode(this.code);
	}

	public ReturnData(Exception e) {
		StringBuilder msg = new StringBuilder();
		msg.append("异常信息：" + e.getMessage());
		msg.append("，异常类：" + e.getClass().getName());
		this.setData(msg);
		// 判断是否属于业务处理直接抛出异常类
		if (e instanceof BizException) {
			BizException biz = (BizException) e;
			if(biz.hasCode()) {
				this.setCode(biz.getCode());
			} else {
				this.code = 0;
				this.msg = biz.getMessage();
			}
		} else {
			this.setCode(ExceptionCodeUtil.getCode(e));
		}
	}

	public ReturnData(Integer code) {
		this.setCode(code);
	}

	public ReturnData(Integer code, Object data) {
		this.setCode(code);
		this.setData(data);
	}

	public ReturnData(Object data) {
		this.setCode(this.code);
		this.setData(data);
	}

	public Integer getCode() {
		return this.code;
	}

	public void setCode(Integer code) {
		if (CommonUtil.isEmpty(code)) {
			code = 0;
		}
		CodeUtil codeUtil = SpringUtil.getBean(CodeUtil.class);
		try {
			this.msg = codeUtil.getString(code);
			this.code = code;
		} catch (Exception e) {
			this.msg = codeUtil.getString(0);
			this.code = 0;
		}
	}

	public void setCode(Integer code, String msg) {
		this.code = code;
		this.msg = msg;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Override
	public String toString() {
		return "DataNoPaging [code=" + code + ", data=" + data + ", msg=" + msg + "]";
	}

}
